<template>
  <div class="violation-container">
    <!-- 搜索表单 -->
    <el-card shadow="hover" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="违规类型">
          <div class="select-label" v-if="searchForm.violationType">
            <span>选择的违规类型: {{ getViolationTypeName(searchForm.violationType) }}</span>
          </div>
          <el-select v-model="searchForm.violationType" clearable placeholder="请选择违规类型">
            <el-option
              v-for="item in violationTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card shadow="hover" class="table-card">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增违规</el-button>
      </div>
      
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%"
        v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        
        <!-- 添加车牌号列 -->
        <el-table-column label="车牌号" width="120" align="center">
          <template #default="scope">
            {{ scope.row.carId || '无法识别' }}
          </template>
        </el-table-column>
        
        <!-- 添加违规图片列 -->
        <el-table-column label="违规图片" width="120" align="center">
          <template #default="scope">
            <el-image 
              v-if="scope.row.imagePath"
              :src="scope.row.imagePath" 
              :preview-src-list="[scope.row.imagePath]"
              style="width: 60px; height: 40px"
              fit="cover">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column label="违规类型" width="120">
          <template #default="scope">
            {{ getViolationTypeName(scope.row.violationType) }}
          </template>
        </el-table-column>
        
        <!-- 添加预警等级列 -->
        <el-table-column label="预警等级" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getWarningLevelType(scope.row.warningLevel)">
              {{ getWarningLevelName(scope.row.warningLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 添加状态列 -->
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'danger' : 'success'">
              {{ scope.row.status === 0 ? '未读' : '已读' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="违规时间" width="180"></el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button size="mini" @click="handleDetail(scope.row)">详情</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination">
      </el-pagination>
    </el-card>
    
    <!-- 新增/编辑弹窗 -->
    <violation-dialog 
      :visible.sync="dialogVisible" 
      :form-data="currentViolation" 
      @refresh="fetchData" />
  </div>
</template>

<script>
import { getViolationPage, deleteViolation, getViolationDetail } from '@/api/violation'
// 修正组件导入路径
import ViolationDialog from '@/components/ViolationDialog.vue'
import { useUserStore } from '@/store/user'

export default {
  components: { ViolationDialog },
  data() {
    return {
      // 搜索表单数据
      searchForm: {
        violationType: '',
        dateRange: []
      },
      // 表格数据
      tableData: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      // 弹窗控制
      dialogVisible: false,
      currentViolation: {},
      // 其他数据
      violationTypes: [
        { label: '超速', value: 1 },
        { label: '违规转弯', value: 2 },
        { label: '压线', value: 3 },
        { label: '机动车闯红灯', value: 4 },
        { label: '行人闯红灯', value: 5 }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  setup() {
    const userStore = useUserStore()
    return { userStore }
  },
  methods: {
    // 获取数据
    fetchData() {
      this.loading = true
      
      // 格式化日期为后端期望的格式 yyyy-MM-dd HH:mm:ss
      let beginTime = null
      let endTime = null
      
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        const formatDate = (date) => {
          if (!date) return null
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        }
        
        beginTime = formatDate(this.searchForm.dateRange[0])
        endTime = formatDate(this.searchForm.dateRange[1])
      }
      
      const params = {
        page: this.pageNum,
        pageSize: this.pageSize, // 修正参数名，从size改为pageSize，与后端DTO保持一致
        violationType: this.searchForm.violationType,
        beginTime: beginTime, // 使用格式化后的日期
        endTime: endTime // 使用格式化后的日期
      }
      
      // 根据用户角色调用不同接口
      // 修正：使用数字角色ID判断，'1'对应管理员
      const isAdmin = this.userStore.userInfo.role === '1' || this.userStore.userInfo.role === '2'
      console.log('当前用户角色:', this.userStore.userInfo.role, '是否管理员:', isAdmin)
      getViolationPage(params, isAdmin).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
      }).catch(error => {
        console.error('获取违法记录失败:', error)
        this.$message.error('获取违法记录失败: ' + (error.message || '未知错误'))
      }).finally(() => {
        this.loading = false
      })
    }
    ,
    // 搜索
    handleSearch() {
      this.pageNum = 1
      this.fetchData()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        violationType: '',
        dateRange: []
      }
      this.handleSearch()
    },
    
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchData()
    },
    
    // 新增
    handleAdd() {
      this.currentViolation = {
        violationType: '',
        description: '',
        location: '克拉玛依市克拉玛依区文轩路',
        status: 0,
        type: 1, // 默认为车辆
        warningLevel: 1 // 默认为低级别
      }
      this.dialogVisible = true
    },
    
    // 详情
    handleDetail(row) {
      // 先加载详情数据
      this.loading = true
      getViolationDetail(row.id).then(response => {
        this.currentViolation = response.data || { ...row }
        this.dialogVisible = true
      }).catch(error => {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败: ' + (error.message || '未知错误'))
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 删除
    handleDelete(id) {
      this.$confirm('确认删除该违规记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteViolation(id).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        }).catch(error => {
          console.error('删除失败:', error)
          this.$message.error('删除失败: ' + (error.message || '未知错误'))
        })
      })
    },
    
    // 获取违规类型名称
    getViolationTypeName(type) {
      const found = this.violationTypes.find(item => item.value === type)
      return found ? found.label : type
    }
    ,
    // 获取预警等级名称
    getWarningLevelName(level) {
      const levelMap = {
        1: '低',
        2: '中', 
        3: '高'
      }
      return levelMap[level] || '未知'
    }
    ,
    // 获取预警等级标签类型
    getWarningLevelType(level) {
      const typeMap = {
        1: 'info',    // 低 - 蓝色
        2: 'warning', // 中 - 橙色
        3: 'danger'   // 高 - 红色
      }
      return typeMap[level] || 'info'
    }
  }
}
</script>

<style scoped>
.violation-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  padding: 18px 0 0 0;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.select-label {
  margin-bottom: 5px;
  font-size: 13px;
  color: #409EFF;
  background-color: #ecf5ff;
  border-radius: 4px;
  padding: 2px 8px;
  display: inline-block;
}
</style>